<template>
  <div v-if="show" class="replay-dialog">
    <div class="dialog-content">
      <h3>对局回放</h3>
      
      <div class="game-info">
        <div class="player-info">
          <div class="white-player">
            <h4>白方: {{ recording?.whitePlayer }}</h4>
            <div class="time">时间: {{ formatTime(recording?.timeControl.initial || 0) }}</div>
          </div>
          <div class="black-player">
            <h4>黑方: {{ recording?.blackPlayer }}</h4>
            <div class="time">时间: {{ formatTime(recording?.timeControl.initial || 0) }}</div>
          </div>
        </div>
        <div class="game-result" v-if="recording?.result">
          结果: {{ recording.result }}
        </div>
      </div>

      <div class="replay-board">
        <div class="chess-board">
          <div v-for="row in 8" :key="row" class="board-row">
            <div 
              v-for="col in 8" 
              :key="col" 
              class="board-cell"
              :class="[
                getCellColor(row, col),
                {
                  'last-move-from': isLastMoveFrom(row-1, col-1),
                  'last-move-to': isLastMoveTo(row-1, col-1)
                }
              ]"
            >
              <ChessPiece
                v-if="getPiece(row-1, col-1)"
                :piece="getPiece(row-1, col-1)"
                :mini="false"
              />
            </div>
          </div>
        </div>

        <div class="move-history">
          <div class="moves-container">
            <div 
              v-for="(move, index) in moveHistory" 
              :key="index"
              class="move-row"
              :class="{ 'current': currentMoveIndex === index }"
              @click="goToMove(index)"
            >
              <div class="move-number">{{ Math.floor(index/2) + 1 }}.</div>
              <div class="move">{{ move }}</div>
              <div 
                v-if="moveComments[index]"
                class="move-comment"
              >
                {{ moveComments[index] }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="replay-controls">
        <div class="playback-controls">
          <button @click="goToStart" :disabled="currentMoveIndex === -1">
            <span>⏮</span>
          </button>
          <button @click="prevMove" :disabled="currentMoveIndex === -1">
            <span>⏪</span>
          </button>
          <button @click="toggleAutoPlay">
            <span>{{ isAutoPlaying ? '⏸' : '▶' }}</span>
          </button>
          <button @click="nextMove" :disabled="currentMoveIndex === (recording?.moves?.length ?? 0) - 1">
            <span>⏩</span>
          </button>
          <button @click="goToEnd" :disabled="currentMoveIndex === (recording?.moves?.length ?? 0) - 1">
            <span>⏭</span>
          </button>
        </div>

        <div class="playback-speed">
          <label>播放速度:</label>
          <select v-model="playbackSpeed">
            <option value="0.5">0.5x</option>
            <option value="1">1x</option>
            <option value="2">2x</option>
            <option value="4">4x</option>
          </select>
        </div>

        <div class="analysis-tools">
          <button @click="toggleAnalysis">
            {{ showAnalysis ? '关闭分析' : '开启分析' }}
          </button>
          <button @click="addComment">添加注释</button>
          <button @click="exportPGN">导出PGN</button>
        </div>
      </div>

      <div v-if="showAnalysis" class="analysis-panel">
        <div class="evaluation-bar">
          <div 
            class="evaluation-fill"
            :style="{ height: `${getEvaluationBarHeight(currentEvaluation)}%` }"
          ></div>
        </div>
        <div class="analysis-info">
          <div class="position-evaluation">
            局面评分: {{ formatEvaluation(currentEvaluation) }}
          </div>
          <div class="best-moves">
            <h4>最佳着法:</h4>
            <div 
              v-for="(move, index) in bestMoves" 
              :key="index"
              class="best-move"
            >
              {{ index + 1 }}. {{ move }}
            </div>
          </div>
        </div>
      </div>

      <div class="dialog-buttons">
        <button @click="$emit('close')">关闭</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import ChessPiece from './ChessPiece.vue'
import { useGameRecorder } from '../composables/useGameRecorder'
import { useChessAI } from '../composables/useChessAI'
import type { GameRecording } from '../types/chess'

const props = defineProps<{
  show: boolean
  recordingId: string
}>()

const emit = defineEmits<{
  (e: 'close'): void
}>()

const { getRecording } = useGameRecorder()

const recording = computed(() => getRecording(props.recordingId))
const currentMoveIndex = ref(-1)
const currentPosition = ref<(string | null)[][]>([])
const isAutoPlaying = ref(false)
const playbackSpeed = ref(1)
const showAnalysis = ref(false)
const currentEvaluation = ref(0)
const bestMoves = ref<string[]>([])
const moveComments = ref<Record<number, string>>({})
const autoPlayInterval = ref<number | null>(null)

const moveHistory = computed(() => recording.value?.moves || [])

const getCellColor = (row: number, col: number) => {
  return (row + col) % 2 === 0 ? 'white-cell' : 'black-cell'
}

const getPiece = (row: number, col: number) => {
  return currentPosition.value[row]?.[col] || null
}

const isLastMoveFrom = (row: number, col: number) => {
  if (currentMoveIndex.value < 0) return false
  const move = recording.value?.moves[currentMoveIndex.value]
  return move?.from.row === row && move?.from.col === col
}

const isLastMoveTo = (row: number, col: number) => {
  if (currentMoveIndex.value < 0) return false
  const move = recording.value?.moves[currentMoveIndex.value]
  return move?.to.row === row && move?.to.col === col
}

const formatTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

const goToMove = (index: number) => {
  currentMoveIndex.value = index
  updatePosition()
  if (showAnalysis.value) {
    analyzePosition()
  }
}

const prevMove = () => {
  if (currentMoveIndex.value > -1) {
    currentMoveIndex.value--
    updatePosition()
  }
}

const nextMove = () => {
  if (currentMoveIndex.value < (recording.value?.moves.length || 0) - 1) {
    currentMoveIndex.value++
    updatePosition()
  }
}

const goToStart = () => {
  currentMoveIndex.value = -1
  updatePosition()
}

const goToEnd = () => {
  currentMoveIndex.value = (recording.value?.moves.length || 0) - 1
  updatePosition()
}

const toggleAutoPlay = () => {
  isAutoPlaying.value = !isAutoPlaying.value
  if (isAutoPlaying.value) {
    startAutoPlay()
  } else {
    stopAutoPlay()
  }
}

const startAutoPlay = () => {
  if (autoPlayInterval.value) return
  autoPlayInterval.value = window.setInterval(() => {
    if (currentMoveIndex.value < (recording.value?.moves.length || 0) - 1) {
      nextMove()
    } else {
      stopAutoPlay()
    }
  }, 1000 / Number(playbackSpeed.value))
}

const stopAutoPlay = () => {
  if (autoPlayInterval.value) {
    clearInterval(autoPlayInterval.value)
    autoPlayInterval.value = null
  }
  isAutoPlaying.value = false
}

const toggleAnalysis = () => {
  showAnalysis.value = !showAnalysis.value
  if (showAnalysis.value) {
    analyzePosition()
  }
}

const analyzePosition = () => {
  // 实现局面分析逻辑
}

const addComment = () => {
  const comment = prompt('请输入注释:')
  if (comment && currentMoveIndex.value >= 0) {
    moveComments.value[currentMoveIndex.value] = comment
  }
}

const exportPGN = () => {
  // 实现PGN导出逻辑
}

const getEvaluationBarHeight = (evaluation: number) => {
  const maxEval = 5
  const normalizedEval = Math.max(-maxEval, Math.min(maxEval, evaluation))
  return 50 + (normalizedEval / maxEval) * 50
}

const formatEvaluation = (evaluation: number) => {
  return evaluation > 0 ? `+${evaluation.toFixed(2)}` : evaluation.toFixed(2)
}

const updatePosition = () => {
  // 实现位置更新逻辑
}

watch(() => props.show, (newVal) => {
  if (newVal) {
    goToStart()
  } else {
    stopAutoPlay()
  }
})

watch(playbackSpeed, () => {
  if (isAutoPlaying.value) {
    stopAutoPlay()
    startAutoPlay()
  }
})

onMounted(() => {
  if (props.show) {
    goToStart()
  }
})

onUnmounted(() => {
  stopAutoPlay()
})
</script>

<style scoped>
.replay-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  min-width: 1000px;
  max-height: 90vh;
  overflow-y: auto;
}

.game-info {
  margin: 20px 0;
  display: grid;
  grid-template-columns: 1fr auto;
  gap: 20px;
}

.player-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.replay-board {
  display: grid;
  grid-template-columns: auto 300px;
  gap: 20px;
  margin: 20px 0;
}

.chess-board {
  width: 500px;
  height: 500px;
  border: 2px solid #333;
}

.board-row {
  display: flex;
  height: 12.5%;
}

.board-cell {
  width: 12.5%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.white-cell {
  background-color: #fff;
}

.black-cell {
  background-color: #b58863;
}

.last-move-from,
.last-move-to {
  background-color: rgba(255, 255, 0, 0.3);
}

.move-history {
  height: 500px;
  overflow-y: auto;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.moves-container {
  padding: 10px;
}

.move-row {
  display: grid;
  grid-template-columns: auto 1fr auto;
  gap: 10px;
  padding: 5px;
  cursor: pointer;
}

.move-row:hover {
  background: #f5f5f5;
}

.move-row.current {
  background: #e3f2fd;
}

.replay-controls {
  display: grid;
  grid-template-columns: auto auto 1fr;
  gap: 20px;
  align-items: center;
  margin: 20px 0;
}

.playback-controls {
  display: flex;
  gap: 10px;
}

.playback-controls button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.analysis-panel {
  display: grid;
  grid-template-columns: 30px 1fr;
  gap: 20px;
  margin: 20px 0;
  height: 200px;
}

.evaluation-bar {
  background: #eee;
  height: 100%;
  position: relative;
}

.evaluation-fill {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to bottom, #4CAF50, #fff);
  transition: height 0.3s ease;
}

.analysis-info {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style> 